﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

public class LuaNguiDemo : MonoBehaviour
{
    private Action luaStart;
    internal const float GCInterval = 1;//1 second 
    float lastGCTime = 0f;
    private LuaTable scriptEnv = null;

    //[LuaCallCSharp]
    //public delegate UIEventListener.VoidDelegate func(GameObject go);

    private void Awake()
    {
        scriptEnv = LuaGlobalEnv.Instance.luaEnv.NewTable();

        //以K-V方式绑定一些C#对象到Lua代码类(NewTable)
        LuaTable meta = LuaGlobalEnv.Instance.luaEnv.NewTable();
        meta.Set("__index", LuaGlobalEnv.Instance.luaEnv.Global);
        scriptEnv.SetMetaTable(meta);
        meta.Dispose();

        scriptEnv.Set("self", this);

        LuaGlobalEnv.Instance.luaEnv.DoString(LuaGlobalEnv.Instance.MyLuaLoader("luanguidemo"), "LuaNguiDemo", null);

        Action luaAwake = scriptEnv.Get<Action>("awake");
        scriptEnv.Get("start", out luaStart);

        if (luaAwake != null)
            luaAwake();
        luaAwake = null;
    }

    // Use this for initialization
    void Start()
    {
        if (luaStart != null)
            luaStart();
    }

    // Update is called once per frame
    void Update()
    {
        //定期清除Lua中未手动清除的绑定
        if (Time.time - lastGCTime > GCInterval)
        {
            LuaGlobalEnv.Instance.luaEnv.Tick();//清除绑定
            lastGCTime = Time.time;
        }
    }

    private void OnDestroy()
    {        
        luaStart = null;
    }
}
